var url = "http://localhost/spork/api/";
var user_id, ifollow, admin = false;

/****************************************
			Stock Callbacks 
*****************************************/

function default_callback(data){
	/*if(data.response==null){
		for(key in data)
			alert(key+" "+data[key]);
		
	}
	else
		alert("data response: "+data.response);*/
}

var reload_callback = function(data){
	window.location.reload();	
}

var do_nothing = function(){}

/****************************************
			Query API
*****************************************/
function api(page,method,data,success,error){
	if(!success)
		var success = default_callback;
	if(!error)
		var error = default_callback;	
	$.ajax( {
        url: url+page,
        type: method,
        data: data,
        success: success,
        error: error
    });
}

/* API call to login a user */
function login(){
	var success = function(data){
		user_id=data.user_id;
		email=data.user_email;
		if(data.admin=="1")
			admin = true;
		window.location = "latest-activity.php";
	}
	var error = function(data){
		var msg = eval('(' + data.response + ')');
		$("#login div.callback_msg").addClass("error").html(msg.error_message);
	}
	api("session/","POST",$("#login").serialize(),success,error);	
}

/* API call to logout current user */
function logout(){
	api(user_id+"/session/","DELETE",null,reload_callback,reload_callback);	
}

/* Post latest activity */
function setLatestActivity(){
	api("latest_activity/","POST","user_id="+user_id,do_nothing,do_nothing);	
}

/* API call to create a new user account */
function signup(){
	var success = function(data){
		window.location = "index.php?signup="+$("input[name=email]:first").val();
	}
	var error = function(data){
		var msg = eval('(' + data.response + ')');
		$("#signup div.callback_msg").addClass("error").html(msg.error_message);
		$("#step-1").show();
		$("#step-2").hide();
		$("form input:first").focus();
	}
	
	if(validate("signup"))
		api("users/","POST",$("#signup").serialize(),success,error);
	else{
		$("#signup div.callback_msg").addClass("error").html("Missing required fields.");
		if($("#step-1 label").hasClass("error")){
			$("#step-1").show();
			$("#step-2").hide();
		}
		$("#signup label.error:first").next("input").focus();
	}
}

function getForgotQuestion(){
	var email = $("input[name=email]").val();
	var success = function(response){
		response = eval('(' + response + ')');
		var q = response['pfq'];
		$("#question").html(q+"<br /><br />");
		$("#question-section").hide();
		$("#answer-section").show();
		$("#answer-section input:first").focus();
	}
	var error = function(response){
		var msg = eval('(' + response.responseText + ')');
		$("#forgot div.callback_msg").addClass("error").html(msg['error_message']);
	}
	api("pfq/","POST","email="+email,success,error);
}

function checkForgotAnswer(){
	var success = function(data){
		window.location = "index.php?update="+$("input[name=email]:first").val();
	}
	var error = function(response){
		var msg = eval('(' + response.responseText + ')');
		$("#forgot div.callback_msg").addClass("error").html(msg['error_message']);	
	}
	api("pfq/","PUT",$("#forgot").serialize(),success,error);
}

/****************************************
			FOLLOWERS
*****************************************/

/* API call to find users */
function search_users(){
	var success = function(data){
		$("#search_results table").html("");
		var result_count = data.length;
		for(var i in data){
			if(data[i]['id']!=user_id){
				displaySearchUserResult(data[i]);
			}
			else
				result_count--;
		}
		if(result_count==0)
			$("#search_results table").html("<tr><td class='whole' colspan=1>No results for 	<i>"+$("#search_users input[type=text]").val()+"</i>.</td></tr>");
	}
	api("users/","GET",$("#search_users").serialize(),success);
}

/* API call for user to follow id */
function follow(id,success){
	api("follow/","POST","id="+id+"&id2="+user_id,success,do_nothing);	
}

/* API call to stop following a user */
function unfollow(id,success){
	api("follow/"+id,"DELETE",null,success,do_nothing);		
}

/* API call to get all users current user is following */
function ifollow(display){
	var success = function(data){
		ifollow = data;
		if(display)
			followme(true);
	}
	api("ifollow/","GET",null,success);	
}

/* API call to get all users following current user */
function followme(display){
	var success = function(data){
		followme = data;
		if(display){
			displayIFollow();
			displayFollowMe();
		}
	}
	api("follow_me/","GET",null,success);	
}

/****************************************
		FOLLOWERS - HELPER FUNCTIONS
*****************************************/

/* Appends a new row to the search_results table */
function displaySearchUserResult(user){
	var row = createRow(user);
	$("#search_results table").append($(row));	
}

/* Changes the onclick and value options of the follow buttons */
function toggleFollow(id){
	var button = $("."+id);
	var src = $(button).attr("src");
	if(src=="images/icons/add.png")
		button = followButton($(button),id);
	else
		button = followButton($(button),id,true);
}

/* Returns a 'follow' or 'stop following' button */
function followButton(button,id,follow){
	if(follow){
		$(button).attr("onClick","unfollow("+id+",toggleFollow("+id+"))")
		.attr("src","images/icons/add.png")
		.attr("title","Follow");
	}else{
		$(button).attr("onClick","follow("+id+",toggleFollow("+id+"))")
		.attr("src","images/icons/minus.png")
		.attr("title","Stop Following");
	}
	return $(button);
}

/* Returns true if user is following id */
function following(id){
	for(var i in ifollow)
		if(ifollow[i]['id']==id)
			return true;
	return false;
}

/* Returns true if user with id is following current user */
function followingMe(id){
	for(var i in followme)
		if(followme[i]['id']==id)
			return true;
	return false;
}

/* Displays all those the current user follows */
function displayIFollow(){
	var table = $("#ifollow");
	var user = "user";
	if(ifollow.length!=1)
		user += "s";
	$(table).html("<tr><td class='whole' colspan=4>You are following <b>"+ifollow.length+"</b> "+user+".<br /><br /></td></tr>");
	for(var i in ifollow){
		var row = createRow(ifollow[i]);
		$(table).append($(row));
	}
}

/* Displays all those following the current user */
function displayFollowMe(){
	var table = $("#followme");
	var user = "user";
	if(followme.length!=1)
		user += "s";
	$(table).html("<tr><td class='whole' colspan=4>You have <b>"+followme.length+"</b> "+user+" following you.<br /><br /></td></tr>");
	for(var i in followme){
		var row = createRow(followme[i],true);
		$(table).append($(row));
	}
}

/* Returns a row populated with a user's data */
var count=0;
function createRow(user,eye){
	var img = $("<img />");
	$(img).attr("src","php/gravatar.php?email="+user['email'])
	.attr("width",40)
	.attr("height",40)
	.attr("title",user['email']);
	var profile = $("<td />");
	$(profile).append($(img));
	
	var td = $("<td />");
	var result = "";
	if(user['nickname'])
		result += user['nickname'];
	$(td).html(result);
	
	var email = $("<td />");
	$(email).html(user['email']);
	
	var actions = $("<td />");
	$(actions).addClass("action");
	
	var actions = $("<td />");
	$(actions).addClass("action");
	
	var recipes = $("<td />");
	$(recipes).addClass("recipes");
	var a = "<a href=\"javascript: userRecipes('"+user['id']+"','"+user['email']+"','"+user['nickname']+"')\">"
	$(recipes).html(a+"View "+user['nickname']+"'s Recipes</a>");
	
	//if found user is following current user
	if(!eye && followingMe(user['id'])){
		var follow = $("<img />");
		$(follow).attr("src","images/icons/eye.png")
		.attr("title",user['nickname']+" is following you!");
		$(actions).append($(follow));
	}
	
	if($("#ifollow").length==0)
		var callback = "toggleFollow("+user['id']+")";
	else
		var callback = "window.location.reload()";
		
	// if admin, add delete user button
	if(user_id!=user['id'] && admin){
		var trash = $("<img />");
		$(trash).attr("src","images/icons/delete.png")
		.attr("id",user['id'])
		.attr("title","Delete "+user['nickname']+" from spork!")
		.attr("display","inline-block")
		.click(function(){ deleteUser($(this).attr("id")); });
		$(actions).append($(trash));
	}
	
	var follow = $("<img />");
	$(follow).attr("class",user['id']);
	if(!following(user['id'])){
		//follow button
		$(follow).attr("src","images/icons/add.png");
		$(follow).attr("onClick","follow("+user['id']+","+callback+")");
		$(follow).attr("title","Follow");
	}
	else{	
		//unfollow button
		$(follow).attr("src","images/icons/minus.png");
		$(follow).attr("onClick","unfollow("+user['id']+","+callback+")");
		$(follow).attr("title","Stop Following");
	}
	$(actions).append($(follow));
	
	var row = $("<tr />");
	$(row).append($(profile));
	$(row).append($(td));
	$(row).append($(email));
	$(row).append($(recipes));
	$(row).append($(actions));
	return row;
}

/****************************************
			RECIPES 
*****************************************/

function addNewRecipe(){
	if(validate("add-recipe")){
		var input = $("#add-recipe").serializeArray();
		input[1]['value'] = buildTagString();
		input[7]['name'] = "ingredient";
		input[7]['value'] = buildIngredientString();
		input[8]['name'] = "direction";
		input[8]['value'] = buildDirectionString();	
		
		if(input[7]['value']=="" || input[8]['value']==""){
			alert("Recipe not saved.  Make sure you've entered ingredients and directions.");
			return;
		}
		
		var data = new Array();
		for(var i=0; i<9; i++){
			var array = new Array();
			array['value'] = input[i]['value'];
			array['name'] = input[i]['name'];
			data[i] = array;
		}
		array = new Array();
		array['name'] = "name";
		array['value'] = $("input[name=name]").val();
		data[9] = array;
		data[8]['name'] = "direction";
		
		//for(var i=0; i<data.length; i++)
			//alert(i+" : "+data[i]['name']+" : "+data[i]['value']);
			
		var success = function(result){
			$("#upload input[name=rid]").val(result['rid']);
			$("#upload input[name=rid]").val();
			uploadPhoto(result['rid']);	
		}
		
		var error = function(result){
			alert(result.responseText);
			var result = eval('(' + result.responseText + ')');
			$("#upload input[name=rid]").val(result['rid']);
			$("#upload input[name=rid]").val();
			//uploadPhoto(result['rid']);	
		}
		
		api("recipe/","POST",data,success,error);
	}else{
		var missing = "";
		var i=0;
		var count = $(".error").length-1;
		$(".error").each(function(){
			var field =  $(this).html();
			field = field.substr(1);
			if(field=="")
				field = "Name";
			missing += field;
			if(i++<count)
				missing +=", ";
		});
		alert("Missing required fields: "+missing);	
	}
}

function getRecipe(refreshPage){
	if(refreshPage){
		window.location.href="view-recipe.php?rid="+$("#recipe_id").attr("value");
		return;
	}
	var success = function(result){
		$("#recipe").css("display","");
		displayRecipe(result);
	};
	api("recipe/"+$("#recipe_id").val(),"GET",null,success,function(result){alert("error "+result.responseText);});	
}

function deleteRecipe(){
	if(!confirm("Are you sure you want to delete this recipe?"))
		return;
	var success = function(result){
		window.location.href = "recipes.php";
	};
	api("recipe/"+$("#recipe_id").attr("value"),"DELETE",null,success,function(result){alert("error "+result.responseText);});
}

function getAllRecipes(){
	var success = function(result){
		alert(result[0]['name']);
	};
	api("all_recipes/"+user_id,"GET",null,success,function(result){alert("error "+result.responseText);});	
}

function favorite(){
	var data = "user_id="+user_id+"&recipe_id="+$("#recipe_id").attr("value");
	var success = function(result){
		$("#favorite").hide();
		$("#unfavorite").show();
	};
	api("favorites/","POST",data,success,function(result){alert("error "+result.responseText);});
}

function unfavorite(){
	var success = function(result){
		$("#unfavorite").hide();
		$("#favorite").show();
	};
	api(user_id+"/favorites/"+$("#recipe_id").attr("value"),"DELETE",null,success,function(result){alert("error "+result.responseText);});
}

function emailRecipe(){
	var email = "kristyacaster@gmail.com";
	var data = "recipe_id="+$("#recipe_id").attr("value")+"&email="+email;
	
	var success = function(result){
		alert("Recipe emailed.");
	};
	
	var error = function(){
		alert("error "+result.responseText);
	}
	
	$.ajax( {
        url: "php/emailRecipe.php",
        type: "POST",
        data: data,
        success: success,
        error: error
    });
	return;
	
	api("email/","POST",data,success,function(result){alert("error "+result.responseText);});
}

function rateRecipe(){
	$("#rate").val("Click to Rate.");
	$("#rate_it").slideDown();
}

function saveRating(passive){
	var rid = $("#recipe_id").attr("value");
	var rating = $("#rate_it div.on").length;
	var data = "recipe_id="+rid+"&rating="+rating;
	
	if(passive)
		var success = null;
	else{
		var success = function(result){ 
			$("#rate").val("Rating Saved.");
		};
	}
	
	api("rating/","POST",data,success,function(result){alert("error "+result.responseText);});
}

/****************************************
		RECIPES - HELPER FUNCTIONS
*****************************************/

function uploadPhoto(){
	$("#upload").submit();
}

function buildIngredientString(){
	var string = "";
	var rows = $(".ingredients span.row").length;
	var added = false;
	for(var i=0; i<rows; i++){
		var row = $(".ingredients span.row").eq(i);
		var quantity = $(row).children("input.quantity").val();
		var ingredient = $(row).children("input.ingredient").val();
		var optional = $(row).children("input.optional:checked").val();
		if(quantity && ingredient){
			
			if(added)
				string += ":";
			
			string += ingredient+"*";
			string += quantity+"*";
			string += $(row).children("select").val()+"*";
			
			if(optional!="on")
				optional = 1;
			else
				optional = 0;
			string += optional;
			
			added = true;
		}
		else
			added = false;
	}
	return string;
}

function buildDirectionString(){
	var string = "";
	var rows = $(".directions span.row").length;
	var added = false;
	for(var i=0; i<rows; i++){
		var row = $(".directions span.row").eq(i);
		var text = $(row).children("textarea").val();
		if(text){
			if(added)
				string += "|";
			
			string += text;
			added = true;
		}
		else
			added = false;
	}
	return string;
}

function buildTagString(){
	var string = $("input[name=tag]").val();
	string = string.replace(/, /g,":");
	string = string.replace(/,/g,":");
	return string;
}

/****************************************
			COMMENTS
*****************************************/

function addComment(){
	var comment = $("#comments textarea:first").val();
	if(comment=="")
		return;
	var data = "comment="+comment+"&recipe_id="+$("#recipe_id").attr("value");
	var success = function(result){
		window.location.reload();
	};
	api("comments/","POST",data,success,function(result){alert("error "+result.responseText);});	
}

function deleteComment(timestamp){
	var data = "timestamp="+timestamp;
	var success = function(result){
		window.location.reload();
	};
	api($("#recipe_id").attr("value")+"/comments/","POST",data,success,function(result){alert("error "+result.responseText);});
}


/****************************************
		ADMIN
*****************************************/
all_users = new Array();
function getAllUsers(){
	var success = function(result){
		all_users = result;
		displayAllUsers();
	};
	api("all_users/","GET",null,success,function(result){alert("error "+result.responseText);});	
}

function deleteUser(id){
	if(!confirm("Are you sure you want to delete this user?"))
		return;
	var success = function(result){
		window.location.reload();
	};
	api("delete_user/"+id,"DELETE",null,success,function(result){alert("error "+result.responseText);});	
}

/****************************************
		ADMIN Helper Functions
*****************************************/

function displayAllUsers(){
	var table = $("#all_users");
	var user = "user";
	if(all_users.length!=1)
		user += "s";
	$(table).html("<tr><td class='whole' colspan=4>There are <b>"+all_users.length+"</b> spork! users.<br /><br /></td></tr>");
	for(var i in all_users){
		var row = createRow(all_users[i],true);
		$(table).append($(row));
	}
}